class PaperSearchApp {
    constructor() {
        this.apiBase = 'http://localhost:8000';
        this.currentPapers = [];
        this.chatHistory = [];
        
        this.initializeElements();
        this.bindEvents();
        this.checkServerStatus();
    }
    
    initializeElements() {
        // 搜索相关元素
        this.searchInput = document.getElementById('searchInput');
        this.searchBtn = document.getElementById('searchBtn');
        this.categoryFilter = document.getElementById('categoryFilter');
        this.sortFilter = document.getElementById('sortFilter');
        this.resultsContainer = document.getElementById('resultsContainer');
        this.resultsList = document.getElementById('resultsList');
        this.loading = document.getElementById('loading');
        
        // 聊天相关元素
        this.chatInput = document.getElementById('chatInput');
        this.sendBtn = document.getElementById('sendBtn');
        this.chatMessages = document.getElementById('chatMessages');
        
        // 模态框相关元素
        this.paperModal = document.getElementById('paperModal');
        this.modalTitle = document.getElementById('modalTitle');
        this.modalContent = document.getElementById('modalContent');
        this.downloadBtn = document.getElementById('downloadBtn');
        this.chatAboutBtn = document.getElementById('chatAboutBtn');
        this.closeModal = document.querySelector('.close');
    }
    
    bindEvents() {
        // 搜索事件
        this.searchBtn.addEventListener('click', () => this.searchPapers());
        this.searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.searchPapers();
        });
        
        // 聊天事件
        this.sendBtn.addEventListener('click', () => this.sendMessage());
        this.chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.sendMessage();
        });
        
        // 模态框事件
        this.closeModal.addEventListener('click', () => this.hideModal());
        this.downloadBtn.addEventListener('click', () => this.downloadPaper());
        this.chatAboutBtn.addEventListener('click', () => this.chatAboutPaper());
        
        // 点击模态框外部关闭
        window.addEventListener('click', (e) => {
            if (e.target === this.paperModal) {
                this.hideModal();
            }
        });
    }
    
    async checkServerStatus() {
        try {
            const response = await fetch(`${this.apiBase}/health`);
            const data = await response.json();
            
            if (data.status === 'healthy') {
                this.showNotification('服务器连接正常', 'success');
            } else {
                this.showNotification('服务器连接异常', 'error');
            }
        } catch (error) {
            this.showNotification('无法连接到服务器', 'error');
            console.error('服务器连接失败:', error);
        }
    }
    
    async searchPapers() {
        const query = this.searchInput.value.trim();
        if (!query) {
            this.showNotification('请输入搜索关键词', 'warning');
            return;
        }
        
        this.showLoading();
        
        try {
            const searchRequest = {
                query: query,
                limit: 10,
                filters: {
                    category: this.categoryFilter.value,
                    sort: this.sortFilter.value
                }
            };
            
            const response = await fetch(`${this.apiBase}/search`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(searchRequest)
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const papers = await response.json();
            this.displayPapers(papers);
            
        } catch (error) {
            console.error('搜索失败:', error);
            this.showNotification('搜索失败，请稍后重试', 'error');
            this.displaySamplePapers();
        }
    }
    
    displayPapers(papers) {
        this.hideLoading();
        this.currentPapers = papers;
        
        if (papers.length === 0) {
            this.resultsList.innerHTML = `
                <div class="no-results">
                    <p>未找到相关论文</p>
                    <p>尝试使用不同的关键词或调整筛选条件</p>
                </div>
            `;
            return;
        }
        
        this.resultsList.innerHTML = papers.map((paper, index) => `
            <div class="paper-card" data-index="${index}">
                <div class="paper-title">${this.escapeHtml(paper.title)}</div>
                <div class="paper-authors">作者: ${paper.authors.join(', ')}</div>
                <div class="paper-abstract">${this.escapeHtml(paper.abstract.substring(0, 200))}...</div>
                <div class="paper-meta">
                    <span>分类: ${paper.categories ? paper.categories.join(', ') : '未知'}</span>
                    <span>相关性: ${(paper.relevance_score * 100).toFixed(1)}%</span>
                </div>
            </div>
        `).join('');
        
        // 绑定点击事件
        document.querySelectorAll('.paper-card').forEach(card => {
            card.addEventListener('click', () => {
                const index = parseInt(card.dataset.index);
                this.showPaperDetails(this.currentPapers[index]);
            });
        });
    }
    
    displaySamplePapers() {
        const samplePapers = [
            {
                title: "Attention Is All You Need",
                authors: ["Ashish Vaswani", "Noam Shazeer", "Niki Parmar"],
                abstract: "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism.",
                categories: ["cs.CL", "cs.LG"],
                relevance_score: 0.95
            },
            {
                title: "BERT: Pre-training of Deep Bidirectional Transformers",
                authors: ["Jacob Devlin", "Ming-Wei Chang", "Kenton Lee"],
                abstract: "We introduce a new language representation model called BERT, which stands for Bidirectional Encoder Representations from Transformers.",
                categories: ["cs.CL"],
                relevance_score: 0.92
            }
        ];
        
        this.displayPapers(samplePapers);
        this.showNotification('使用示例数据展示', 'info');
    }
    
    async sendMessage() {
        const message = this.chatInput.value.trim();
        if (!message) return;
        
        this.addMessage(message, 'user');
        this.chatInput.value = '';
        
        try {
            const chatRequest = {
                question: message,
                chat_history: this.chatHistory
            };
            
            const response = await fetch(`${this.apiBase}/chat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(chatRequest)
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const chatResponse = await response.json();
            this.addMessage(chatResponse.answer, 'bot');
            
            // 更新聊天历史
            this.chatHistory.push(
                { role: 'user', content: message },
                { role: 'assistant', content: chatResponse.answer }
            );
            
        } catch (error) {
            console.error('聊天失败:', error);
            this.addMessage('抱歉，暂时无法回答您的问题。请检查网络连接或稍后重试。', 'bot');
        }
    }
    
    addMessage(content, role) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${role}-message`;
        messageDiv.innerHTML = `
            <div class="message-content">${this.escapeHtml(content)}</div>
        `;
        
        this.chatMessages.appendChild(messageDiv);
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }
    
    showPaperDetails(paper) {
        this.modalTitle.textContent = paper.title;
        this.modalContent.innerHTML = `
            <div class="paper-details">
                <p><strong>作者:</strong> ${paper.authors.join(', ')}</p>
                <p><strong>分类:</strong> ${paper.categories ? paper.categories.join(', ') : '未知'}</p>
                <p><strong>摘要:</strong></p>
                <div class="abstract-content">${this.escapeHtml(paper.abstract)}</div>
                ${paper.published ? `<p><strong>发布时间:</strong> ${new Date(paper.published).toLocaleDateString()}</p>` : ''}
                ${paper.pdf_url ? `<p><strong>PDF链接:</strong> <a href="${paper.pdf_url}" target="_blank">${paper.pdf_url}</a></p>` : ''}
            </div>
        `;
        
        this.downloadBtn.dataset.paperId = paper.id;
        this.chatAboutBtn.dataset.paperTitle = paper.title;
        
        this.showModal();
    }
    
    showModal() {
        this.paperModal.style.display = 'block';
    }
    
    hideModal() {
        this.paperModal.style.display = 'none';
    }
    
    downloadPaper() {
        const paperId = this.downloadBtn.dataset.paperId;
        if (paperId) {
            window.open(`${this.apiBase}/paper/${paperId}/download`, '_blank');
            this.showNotification('开始下载论文', 'success');
        }
    }
    
    chatAboutPaper() {
        const paperTitle = this.chatAboutBtn.dataset.paperTitle;
        if (paperTitle) {
            this.chatInput.value = `请介绍一下论文《${paperTitle}》的主要内容和创新点`;
            this.sendMessage();
            this.hideModal();
        }
    }
    
    showLoading() {
        this.loading.style.display = 'block';
        this.resultsList.innerHTML = '';
    }
    
    hideLoading() {
        this.loading.style.display = 'none';
    }
    
    showNotification(message, type = 'info') {
        // 简单的通知实现
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.textContent = message;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 5px;
            color: white;
            z-index: 1001;
            font-weight: bold;
            transition: all 0.3s ease;
        `;
        
        if (type === 'success') {
            notification.style.background = '#28a745';
        } else if (type === 'error') {
            notification.style.background = '#dc3545';
        } else if (type === 'warning') {
            notification.style.background = '#ffc107';
            notification.style.color = '#212529';
        } else {
            notification.style.background = '#17a2b8';
        }
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.style.opacity = '0';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }
    
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 应用初始化
document.addEventListener('DOMContentLoaded', () => {
    new PaperSearchApp();
});